#!/usr/bin/env python

import os
import time
# import gc
# import inspect


def get_func():
    from inspect import currentframe, getframeinfo
    caller = currentframe().f_back
    func_name = getframeinfo(caller)[2]
    caller = caller.f_back
    from pprint import pprint
    func = caller.f_locals.get(
            func_name, caller.f_globals.get(
                func_name
        )
    )

    return func


class TLog(object):
    def __init__(self, path='/opt/fusionstack/log/pytrace.log'):
        self.path = path
        self.count = 0

        self.reset()

    def reset(self):
        try:
            st = os.stat(self.path)
            if st.st_size > 10 * 1024 * 1024:
                self.write('reset', reset=True)
        except:
            pass

    def write(self, ctx='', msg='', tty=False, reset=False):
        try:
            oflag = 'w' if reset else 'a'
            with open(self.path, oflag) as f:
                self.count += 1
                msg = '%8d %s %s:%s' % (self.count, time.ctime(), ctx, msg)
                f.write('%s\n' % msg)
                if tty:
                    print msg
        except:
            pass


tlog = TLog()


def main():
    tl = TLog(path='./pytrace.log')
    tl.write(ctx=get_func(), msg='a')
    tl.write(ctx=get_func(), msg='b')
    tl.write(ctx=get_func(), msg='c')


if __name__ == '__main__':
    main()
